<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
import { getLogsApi, getLogTypeApi } from "@/api/user"


// 响应式数据
const timeRange = ref([])
const logLevels = ref(['INFO', 'WARNING', 'ERROR'])
const searchText = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const detailDialogVisible = ref(false)
const currentDetail = ref({})
const loading = ref(false)
const logs = ref([])
const totalLogs = ref(0)
const levelOptions = ref([])


// 获取日志数据
const fetchLogs = async () => {
    loading.value = true
    try {
        const params = {
            page: currentPage.value,
            per_page: pageSize.value,
            level: logLevels.value.join(','),
            search: searchText.value,
        }

        // 添加时间范围参数
        if (timeRange.value && timeRange.value.length === 2) {
            const [start, end] = timeRange.value
            params.start_time = start.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }).replace(/\//g, '-').replace(/\b(\d)\b/g, '0$1').replace(/, /g, ' ')

            params.end_time = end.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }).replace(/\//g, '-').replace(/\b(\d)\b/g, '0$1').replace(/, /g, ' ')
        }
        const response = await getLogsApi(params)

        logs.value = response.data.logs
        totalLogs.value = response.data.total
    } catch (error) {
        console.error('获取日志失败:', error)
        ElMessage.error('获取日志失败')
    } finally {
        loading.value = false
    }
}
// 获取日志级别选项
const fetchLogLevels = async () => {
    try {
        const response = await getLogTypeApi()
        levelOptions.value = response.data.log_type.map(level => ({
            value: level,
            label: level
        }))
    } catch (error) {
        console.error('获取日志级别失败:', error)
    }
}
// 监听筛选条件变化
watch([timeRange, logLevels, searchText, currentPage, pageSize], () => {
    fetchLogs()
}, { deep: true })

// 方法
const showDetails = (log) => {
    currentDetail.value = log
    detailDialogVisible.value = true
}

const getLevelClass = (level) => {
    return {
        'log-info': level === 'INFO',
        'log-warning': level === 'WARNING',
        'log-error': level === 'ERROR'
    }
}


const getTagType = (level) => {
    switch (level) {
        case 'INFO': return ''
        case 'WARNING': return 'warning'
        case 'ERROR': return 'danger'
        default: return 'info'
    }
}

// 初始化
onMounted(() => {
    fetchLogLevels()
    fetchLogs()
})
</script>
  

<template>
    <page-container title="日志查询">

        <div class="log-toolbar">
            <!-- 左侧筛选条件 -->
            <div class="filter-section">
                <el-form :inline="true">
                    <el-form-item label="时间范围">
                        <el-date-picker v-model="timeRange" type="datetimerange" range-separator="至"
                            start-placeholder="开始时间" end-placeholder="结束时间" />
                    </el-form-item>

                    <el-form-item label="日志级别">
                        <el-select v-model="logLevels" multiple placeholder="请选择">
                            <el-option v-for="level in levelOptions" :key="level.value" :label="level.label"
                                :value="level.value" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 右侧搜索和排序 -->
            <div class="action-section">
                <el-input v-model="searchText" placeholder="搜索日志内容" class="search-input" clearable>
                    <template #prefix>
                        <el-icon>
                            <search />
                        </el-icon>
                    </template>
                </el-input>
            </div>
        </div>

        <!-- 日志表格 -->
        <el-table :data="logs" border style="width: 100%" class="log-table">
            <el-table-column prop="timestamp" label="时间" width="180" sortable />
            <el-table-column prop="username" label="用户" width="120" />
            <el-table-column prop="action" label="操作">
                <template #default="{ row }">
                    <span :class="getLevelClass(row.level)">{{ row.action }}</span>
                </template>
            </el-table-column>
            <el-table-column label="详情" width="80">
                <template #default="{ row }">
                    <el-button v-if="row.details" type="text" @click="showDetails(row)">
                        查看
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalLogs"
                :page-sizes="[2, 3, 5, 10]" layout="total, sizes, prev, pager, next, jumper" />
        </div>

        <!-- 日志详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="日志详情" width="50%">
            <div class="log-detail">
                <p><strong>时间:</strong> {{ currentDetail.timestamp }}</p>
                <p><strong>用户:</strong> {{ currentDetail.username }}</p>
                <p><strong>级别:</strong>
                    <el-tag :type="getTagType(currentDetail.level)">
                        {{ currentDetail.level }}
                    </el-tag>
                </p>
                <p><strong>操作:</strong> {{ currentDetail.action }}</p>
                <el-divider />
                <p><strong>详细信息:</strong></p>
                <pre>{{ currentDetail.details }}</pre>
            </div>
        </el-dialog>
    </page-container>
</template>
  

<style scoped>
.log-container {
    padding: 20px;
}

.log-card {
    min-height: calc(100vh - 40px);
}

.card-header {
    font-size: 18px;
    font-weight: bold;
}

.log-toolbar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.filter-section {
    flex: 1;
}

.action-section {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 10px;
}

.search-input {
    width: 250px;
}

.sort-section {
    display: flex;
    align-items: center;
    gap: 10px;
}

.log-table {
    margin-top: 20px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.log-info {
    color: var(--el-color-info);
}

.log-warning {
    color: var(--el-color-warning);
}

.log-error {
    color: var(--el-color-danger);
}

.log-detail pre {
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    white-space: pre-wrap;
}
</style>